<?php
// +----------------------------------------------------------------------
// | CRMUU-企微SCRM是专业的企业微信第三方源码系统.
// +----------------------------------------------------------------------
// | [CRMUU] Copyright (c) 2022 http://crmuu.com All rights reserved.
// +----------------------------------------------------------------------

namespace app\wework\controller\user\send;

use think\facade\Db;
use think\facade\Log;
use app\BaseController;
use app\wework\controller\Base;
use app\wework\model\Basemodel;
use think\facade\Session;
use app\wework\model\QyWechatApi;
use app\wework\model\user\send\MassSendModel;
use app\wework\model\user\send\GroupSendModel;
include "../extend/PHPExcel/php-excel.class.php";


class GroupSend extends Base
{
	/*
	* 客户群群发列表
	*/
    public function index(){
		$page = $this->req->param("page")?:1;
        $size = $this->req->param("size")?:10;
		$times = $this->req->param("times");
		$name = $this->req->param("name");
		$res = GroupSendModel::getList($page,$times,$name,$size);
    	return success('客户群群发列表',$res);
    }

	/**
	 * 添加客户群群发
	 * @param $staffer 选择员工列表 ALL为全部
	 * @param $name 名称
	 * @param $content 群发内容
	 * @param $adjunct_data 附件内容
	 * @param $send_status 群发规则，1为立即群发，2为定时群发
	 * @param $send_time 群发时间
	 * @param 
	 * @param 暂时没做详情数据
	 * @return 
	 */
	public function addMsg(){
		$wid = Session::get('wid');
        $name = $this->req->param("name");
        $staffer = $this->req->param("staffer");
        if(!$staffer)$staffer = MassSendModel::getAlls();
    	$department = $this->req->param("department");
        if(!$name) return error("参数错误");
        $content = $this->req->param("content");
    	$adjunct_data = $this->req->param("adjunct_data");
    	$send_status = $this->req->param("send_status");
    	$send_time = $this->req->param("send_time")?:date("Y-m-d H:i:s");
    	$res = GroupSendModel::addMsg($name,$staffer,$content,$adjunct_data,$send_status,$send_time);
    	if($send_status == 1){
    		// $content = ["content"=>$content];
    		$attachments = GroupSendModel::assembleOther($adjunct_data,$wid);
    		$groiup_list = GroupSendModel::getStaffer($staffer);
    		foreach($groiup_list as $value){
    			$add = QyWechatApi::addMsgGroup($wid,$value["userid"],$content,$attachments,"group");
    			if($add["errcode"] == 0){
					$msg_id = GroupSendModel::addMsgid($value["id"],$res,$add["msgid"]);
                    GroupSendModel::addDetails($wid,$msg_id,$res,$value["id"]);
				}else{
                    return error("操作失败",$add['errcode']);
                }
    		}
    	}
    	return success('添加客户群群发',$res);
	}

	/**
    * 客户群群发详情 初始化基本数据
    */
    public function getMsg(){
        $id = $this->req->param("id");
        if(!$id) return error("参数错误");
        $msg = GroupSendModel::getMsg($id);
        $getData = GroupSendModel::getData($id);

        $data["list"] = $msg;
        $data["detail"] = $getData;
        return success('群发详情',$data);
    }

    //groupdownexcel
    public function downexcel(){
        $type = $this->req->param("type")?:1;
        $wid = $this->req->param("wid");
        $id = $this->req->param("id");
        if(!$wid || !$id) return error("参数错误");
        $status = $this->req->param("status");
        if($type == 1){
            $str = "客户群群发-客户群接收详情";
            $res = GroupSendModel::getGroupAll($id,NULL,$status);
            $arr = [
                0 => ['群聊名称','群主名称','群主所在部门',"消息送达状态","创建时间"]
            ];
            $i = 1;
            foreach($res as $value){
                $arr[$i]["群聊名称"] = $value["name"];
                $arr[$i]["群主名称"] = $value["staff"]["name"];
                $arr[$i]["群主所在部门"] = implode(",", $value["staff"]["department"]);
                if($value["status"] == 0)$arr[$i]["消息送达状态"] = "未发送";
                if($value["status"] == 1)$arr[$i]["消息送达状态"] = "已发送";
                if($value["status"] == 2)$arr[$i]["消息送达状态"] = "发送失败-因客户群已收到其他消息提醒";
                $arr[$i]["创建时间"] = $value["create_time"]?:"-";
                $i++;
            }
        }else{
            $str = "客户群群发-群主发送详情";
            $staff_id = $this->req->param("staff_id");
            if($staff_id)$staff_id = explode(",",$staff_id);
            $res = GroupSendModel::getUserAll($id,$staff_id,$status);
            $arr = [
                0 => ['群主名称','群主所在部门',"消息发送状态","本次群发发送群聊总数","已发送群聊数量","发送时间"]
            ];
            $i = 1;
            foreach($res as $value){
                $arr[$i]["群主名称"] = $value["staff"]["name"];
                $arr[$i]["群主所在部门"] = implode(",", $value["department"]);
                if($value["status"] == 0)$arr[$i]["消息发送状态"] = "未发送";
                if($value["status"] == 1)$arr[$i]["消息发送状态"] = "已发送";
                if($value["status"] == 2)$arr[$i]["消息发送状态"] = "发送失败-因客户群已收到其他消息提醒";
                $arr[$i]["本次群发发送群聊总数"] = $value["group_size"];
                $arr[$i]["已发送群聊数量"] = $value["send_size"];
                $arr[$i]["发送时间"] = $value["time"];
                $i++;
            }
        }

        $xls = new \Excel_XML('utf-8', false, '数据导出');
        $xls->addArray($arr);
        $xls->generateXML($str.date('Y-m-d H:i:s'),time());
        exit();
    }

    /**
    * 客户群群发详情 初始化基本数据
    */
    public function getGroupAll(){
        $id = $this->req->param("id");
        if(!$id) return error("参数错误");
        $name = $this->req->param("name");
        $status = $this->req->param("status");
        $getData = GroupSendModel::getGroupAll($id,$name,$status);

        return success('群发详情',$getData);
    }

    /**
    * 客户群群发详情 初始化基本数据
    */
    public function getUserAll(){
        $id = $this->req->param("id");
        if(!$id) return error("参数错误");
        $status = $this->req->param("status");
        $staff_id = $this->req->param("staff_id");
        $getData = GroupSendModel::getUserAll($id,$staff_id,$status);

        return success('群发详情',$getData);
    }

    //更新 
    public function upds(){
        $wid = Session::get('wid');
        $id = $this->req->param("id");
        if(!$id) return error("参数错误");
        GroupSendModel::updateTime($id); //修改同步时间
        $msgidList = Db::table('kt_wework_groupmsgid')->where(["wid"=>$wid,"pid"=>$id])->select()->toArray();
        foreach ($msgidList as $msg) {
            $user = GroupSendModel::getUser($msg["staff_id"]);
            $res = QyWechatApi::getGroupmsgSendResult($wid,$user["userid"],$msg["msgid"]);
            if(count($res["send_list"])){
                GroupSendModel::addDetail($res["send_list"],$wid,$msg);
                $msgSet = GroupSendModel::msgSet($msg["id"]);
            }
            GroupSendModel::updateTime($msg["pid"]);
        }

        return success('更新成功');
    }
    
    //提醒
    public function alertGroup(){
        $wid = Session::get('wid');
        $id = $this->req->param("id");
        $staff_id = $this->req->param("staff_id");
        if(!$staff_id || !$id) return error("参数错误");
        $user = GroupSendModel::getUser($staff_id);
        $msg = GroupSendModel::getMsg($id);
        $str = "【任务提醒】有新的任务啦！";
        $str .= "<br/>";
        $str .= "<br/>";
        $str .= "任务类型：客户群群发任务";
        $str .= "<br/>";
        $str .= "<br/>";
        $str .= "任务名称：".$msg["name"];
        $str .= "<br/>";
        $str .= "<br/>";
        $str .= "创建时间：".$msg["ctime"];
        $str .= "<br/>";
        $str .= "<br/>";
        $str .= "可前往【客户群】中确认发送，记得及时完成哦";
        $res = QyWechatApi::sendText($wid,$user["userid"],$str);
        return success('提醒成功',$res);
    }

    //提醒全部
    public function alertGroups(){
        $wid = Session::get('wid');
        $id = $this->req->param("id");
        if(!$id) return error("参数错误");
        $msg = GroupSendModel::getMsg($id);
        $detailList = GroupSendModel::getDetailList($id);
        foreach($detailList as $value){
            $user = GroupSendModel::getUser($value["staff_id"]);
            $str = "【任务提醒】有新的任务啦！";
            $str .= "<br/>";
            $str .= "<br/>";
            $str .= "任务类型：客户群群发任务";
            $str .= "<br/>";
            $str .= "<br/>";
            $str .= "任务名称：".$msg["name"];
            $str .= "<br/>";
            $str .= "<br/>";
            $str .= "创建时间：".$msg["ctime"];
            $str .= "<br/>";
            $str .= "<br/>";
            $str .= "可前往【客户群】中确认发送，记得及时完成哦";
            $res = QyWechatApi::sendText($wid,$user["userid"],$str);
            if($res["errcode"] != 0){
                return error("错误",$res);
            }
        }
        return success('提醒成功');
    }


    public function sync(){
        $wid = Session::get('wid');
        $msgidList = Db::table('kt_wework_groupmsgid')->where(["wid"=>$wid,"status"=>2])->select()->toArray();
        $mh = curl_multi_init();
        $conn = [];
        $res = [];
        $url = $this->req->domain()."/wework/user/send/groupsyncs";
        for ($i=0;$i<count($msgidList);$i++) {
            $data = http_build_query(["msg"=>$msgidList[$i],"wid"=>$wid]);
            $conn[$i]=curl_init($url);
            curl_setopt($conn[$i],CURLOPT_RETURNTRANSFER,1); //如果成功只将结果返回，不自动输出任何内容
            curl_setopt($conn[$i],CURLOPT_TIMEOUT,0);
            curl_setopt($conn[$i], CURLOPT_POSTFIELDS, $data); //post 传参
            curl_multi_add_handle ($mh,$conn[$i]);
        }
        do { $n=curl_multi_exec($mh,$active); }
        while ($active);
        $result = true;
        for ($i=0;$i<count($msgidList);$i++) {
            $res[$i]=curl_multi_getcontent($conn[$i]);
            curl_close($conn[$i]);
            if($res[$i] != 1){
                $result = false;
            }
        }

        return success("同步成功");
    }

    public function syncs(){
        $msg = $_POST["msg"];
        $wid = $msg["wid"];
        $user = GroupSendModel::getUser($msg["staff_id"]);
        $res = QyWechatApi::getGroupmsgSendResult($wid,$user["userid"],$msg["msgid"]);
        if(count($res["send_list"])){
            GroupSendModel::addDetail($res["send_list"],$wid,$msg);
            $msgSet = GroupSendModel::msgSet($msg["id"]);
        }
        GroupSendModel::updateTime($msg["pid"]);

        return success("同步成功");
    }
}